{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Notebook written by [Zhedong Zheng](https://github.com/zhedongzheng)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "pip3 install rdflib\n",
    "\"\"\"\n",
    "import rdflib\n",
    "import urllib.parse\n",
    "import pprint\n",
    "import itertools\n",
    "import os\n",
    "import sys\n",
    "import time\n",
    "from tqdm import tqdm\n",
    "\n",
    "sys.path.append(os.path.dirname(os.getcwd()))\n",
    "from data import WN18"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "URI_PREFIX = 'http://example.org/'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "def read_triples(path):\n",
    "    triples = []\n",
    "    with open(path, 'rt') as f:\n",
    "        for line in f.readlines():\n",
    "            s, p, o = line.split()\n",
    "            triples += [(s.strip(), p.strip(), o.strip())]\n",
    "    return triples\n",
    "\n",
    "def load_triple():\n",
    "    WN18.download()\n",
    "    triples_tr = read_triples('../data/WN18/wn18/train.txt')\n",
    "    triples_va = read_triples('../data/WN18/wn18/valid.txt')\n",
    "    triples_te = read_triples('../data/WN18/wn18/test.txt')\n",
    "    triples_all = triples_tr + triples_va + triples_te\n",
    "    return triples_all, triples_tr, triples_va, triples_te\n",
    "\n",
    "def get_resources(triples):\n",
    "    return set([r for triple in triples for r in triple])\n",
    "\n",
    "def to_uri(suffix):\n",
    "    return URI_PREFIX + urllib.parse.quote(suffix)\n",
    "\n",
    "def glance_dict(d, n=5):\n",
    "    return dict(itertools.islice(d.items(), n))\n",
    "\n",
    "def build_rdf_graph(triples):\n",
    "    graph = rdflib.Graph()\n",
    "    resources = get_resources(triples)\n",
    "    resource2uri = {r: to_uri(r) for r in resources}\n",
    "    uri2resource = {uri: r for r, uri in resource2uri.items()}\n",
    "    for (s, p, o) in tqdm(triples, total=len(triples), ncols=70):\n",
    "        s_uri = rdflib.URIRef(resource2uri[s])\n",
    "        p_uri = rdflib.URIRef(resource2uri[p])\n",
    "        o_uri = rdflib.URIRef(resource2uri[o])\n",
    "        graph.add((s_uri, p_uri, o_uri))\n",
    "    return graph, uri2resource"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████████████████| 141442/141442 [00:05<00:00, 25679.66it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Query Spent 1.51 sec\n",
      "Get 1 / 141442 Results\n",
      "[('03963645', '_has_part', '04371774')]\n"
     ]
    }
   ],
   "source": [
    "tgt_p, tgt_o = '_has_part', '04371774'\n",
    "\n",
    "triples_all, triples_tr, triples_va, triples_te = load_triple()\n",
    "rdf_graph, uri2resource = build_rdf_graph(triples_tr)\n",
    "query_str = (\n",
    "    \"\"\"\n",
    "    PREFIX prefix: <%s>\n",
    "    \n",
    "    SELECT DISTINCT ?s WHERE {\n",
    "        ?s prefix:%s prefix:%s .\n",
    "    }\n",
    "    \"\"\" % (URI_PREFIX, tgt_p, tgt_o)\n",
    ")\n",
    "\n",
    "t0 = time.time()\n",
    "res = []\n",
    "count = 0\n",
    "for row in rdf_graph.query(query_str):\n",
    "    s = uri2resource[row.s.toPython()]\n",
    "    res.append((s, tgt_p, tgt_o))\n",
    "    count += 1\n",
    "\n",
    "print(\"Query Spent %.2f sec\" % (time.time() - t0))\n",
    "print(\"Get %d / %d Results\" % (count, len(triples_tr)))\n",
    "pprint.pprint(res)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
